package com.ztesoft.web.baseconfig.service.impl;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ztesoft.core.common.Page;
import com.ztesoft.core.convert.IArgConversionService;
import com.ztesoft.core.idproduce.ISequenceGenerator;
import com.ztesoft.framework.exception.BaseAppException;
import com.ztesoft.framework.log.ZTEsoftLogManager;
import com.ztesoft.framework.util.Utils;
import com.ztesoft.web.baseconfig.db.arg.DmStrategyArg;
import com.ztesoft.web.baseconfig.db.arg.SubTableDefineArg;
import com.ztesoft.web.baseconfig.db.arg.SubTableDefineArg.SubTableDefineCriteria;
import com.ztesoft.web.baseconfig.db.dao.DmPlanDao;
import com.ztesoft.web.baseconfig.db.dao.DmPlanRelationDao;
import com.ztesoft.web.baseconfig.db.dao.DmSrcTableDao;
import com.ztesoft.web.baseconfig.db.dao.DmStrategyDao;
import com.ztesoft.web.baseconfig.db.dao.DmTableRelDao;
import com.ztesoft.web.baseconfig.db.dao.SubTableDefineDao;
import com.ztesoft.web.baseconfig.db.po.DmPlanPO;
import com.ztesoft.web.baseconfig.db.po.DmPlanRelationPO;
import com.ztesoft.web.baseconfig.db.po.DmSrcTablePO;
import com.ztesoft.web.baseconfig.db.po.DmStrategyDataobjRelPO;
import com.ztesoft.web.baseconfig.db.po.DmStrategyPO;
import com.ztesoft.web.baseconfig.db.po.DmTableRelPO;
import com.ztesoft.web.baseconfig.db.po.StrategyNodePO;
import com.ztesoft.web.baseconfig.db.po.SubTableDefinePO;
import com.ztesoft.web.baseconfig.db.po.SubTablePO;
import com.ztesoft.web.baseconfig.db.po.TableNamePO;
import com.ztesoft.web.baseconfig.service.IDmPlanRelationService;
import com.ztesoft.web.baseconfig.service.IDmSrcTableService;
import com.ztesoft.web.baseconfig.service.IDmStrategyDataobjRelService;
import com.ztesoft.web.baseconfig.service.IDmStrategyService;
import com.ztesoft.web.baseconfig.service.IDmTableRelService;
import com.ztesoft.web.baseconfig.service.ISubTableDefineService;
import com.ztesoft.web.common.DMSConstant.Status;

/**
 * <Description> <br>
 * 
 * @author lin.jie<br>
 * @version 1.0<br>
 * @taskId <br>
 * @CreateDate 2015年8月4日 <br>
 * @since V1.0<br>
 * @see com.ztesoft.web.baseconfig.service.impl <br>
 */

@Service("dmStrategyService")
public class DmStrategyServiceImpl implements IDmStrategyService {

	private static final ZTEsoftLogManager logger = ZTEsoftLogManager.getLogger(DmStrategyServiceImpl.class);

	@Autowired
	private DmStrategyDao dmStrategyDao;

	@Autowired
	private IDmPlanRelationService dmPlanRelationService;
	@Autowired
	private IDmStrategyDataobjRelService dmStrategyDataobjRelService;
	@Autowired
	private IDmSrcTableService dmSrcTableService;
	@Autowired
	private ISubTableDefineService subTableDefineService;
	@Autowired
	private IDmTableRelService dmTableRelService;

	@Autowired
	private DmPlanRelationDao dmPlanRelationDao;
	@Autowired
	private SubTableDefineDao subTableDefineDao;
	@Autowired
	private DmSrcTableDao dmSrcTableDao;
	@Autowired
	private DmTableRelDao dmTableRelDao;
	@Autowired
	private DmPlanDao dmPlanDao;

	/**
	 * 查询条件转换成Arg类的服务接口
	 */
	@Resource(name = "defaultArgConversionService")
	private IArgConversionService argConversionService;

	/**
	 * 主键生成器
	 */
	@Resource(name = "sequenceProcGenerator")
	private ISequenceGenerator sequenceGenerator;

	@Override
	public DmStrategyPO selectByPrimaryKey(Integer key) throws BaseAppException {
		return dmStrategyDao.selectByPrimaryKey(key);
	}

	/**
	 * 获取有关策略的所有信息，包括源数据、目标数据等
	 * 
	 * @param dmStrategyId
	 * @return
	 * @throws BaseAppException
	 */
	@Override
	public DmStrategyPO getStrategyAllInfo(Integer key) throws BaseAppException {
		return dmStrategyDao.getStrategyAllInfo(key);
	}

	@Override
	public List<DmStrategyPO> selectByArg(DmStrategyPO record) throws BaseAppException {
		logger.debug("selectByArg begin...record={0}", record);
		DmStrategyArg arg = argConversionService.invokeArg(DmStrategyArg.class, record);
		return dmStrategyDao.selectByArg(arg);
	}

	@Override
	public List<DmStrategyPO> selectByPlanId(Integer dmPlanId) throws BaseAppException {
		logger.debug("selectByArg begin...dmPlanId={0}", dmPlanId);
		return dmStrategyDao.selectByPlanId(dmPlanId);
	}

	@Override
	public StrategyNodePO[] selectAllForTree(DmStrategyPO record) throws BaseAppException {
		logger.debug("selectByArg begin...record={0}", record);
		// { id:11, pId:0, name:"父节点11 - 折叠", open:true, drag:false},策略
		// { id:111, pId:11, name:"叶子节点111", Threads:3},策略组
		record.setState(Status.SUCCESS.toString());
		List<StrategyNodePO> strategyList = dmStrategyDao.selectAllForTree(record);
		int listSize = strategyList.size();
		if (strategyList.size() == 0) {
			return strategyList.toArray(new StrategyNodePO[0]);
		} else {
			int groupNum = 1;
			StrategyNodePO po_0 = new StrategyNodePO();
			po_0.setId(strategyList.get(0).getpId());
			po_0.setpId(0);
			po_0.setName("策略组" + groupNum);
			po_0.setOpen(true);
			po_0.setDrag(false);
			strategyList.add(po_0);
			for (int i = 0; i < listSize - 1; i++) {
				if (strategyList.get(i).getpId().equals(strategyList.get(i + 1).getpId())) {
					continue;
				} else {
					groupNum++;
					StrategyNodePO po = new StrategyNodePO();
					po.setId(strategyList.get(i + 1).getpId());
					po.setpId(0);
					po.setName("策略组" + groupNum);
					po.setOpen(true);
					po.setDrag(false);
					strategyList.add(po);
				}
			}
			return strategyList.toArray(new StrategyNodePO[0]);
		}
	}

	@Override
	public Page<DmStrategyPO> selectByArgAndPage(DmStrategyPO record, Page<DmStrategyPO> resultPage)
			throws BaseAppException {
		logger.debug("selectByArgAndPage begin...record={0}", record);
		DmStrategyArg arg = argConversionService.invokeArg(DmStrategyArg.class, record);
		resultPage = dmStrategyDao.selectByArgAndPage(arg, resultPage);
		return resultPage;
	}

	/**
	 * 保存到草稿箱：保证策略名称不同 1、用户新增策略的中途，保存草稿 2、草稿箱列表，编辑
	 * 
	 * @return 0：存在相同名称的计划，不可以保存草稿
	 */
	@Override
	public int addForDraft(DmStrategyPO record) throws BaseAppException {
		logger.debug("add begin...record={0}", record);
		int num = dmStrategyDao.selectByStrategyName(record.getStrategyName());
		if (num != 0) {// 存在相同名称的策略，不可以保存草稿
			return 0;
		} else {// 不存在相同名称的策略，可以保存草稿
			// true:update,false:insert
			boolean isUpdate = false;
			Date nowDate = new Date();
			// 通过前台传回来的ID，从数据库里找，是否已经有这条数据了
			DmStrategyPO po = dmStrategyDao.selectByPrimaryKey(record.getDmStrategyId());
			if (Utils.isEmpty(po)) {// 不存在这条草稿
				isUpdate = false;
				// 获取主键
				int pkId = sequenceGenerator.sequenceIntValue("DM_STRATEGY", "DM_STRATEGY_ID");
				record.setDmStrategyId(pkId);
				record.setSeqNbr(1);
			} else {
				isUpdate = true;
				record.setSeqNbr(po.getSeqNbr());
			}
			record.setConcurrentNumber(1);
			record.setState(Status.DRAFT.toString());
			record.setStateDate(nowDate);
			// 判断执行什么操作
			if (isUpdate) {
				dmStrategyDao.updateByPrimaryKey(record);
			} else {
				dmStrategyDao.insertSelective(record);
			}
			return record.getDmPlanId();
		}
	}

	/**
	 * 新增提交，保证策略名称不同
	 * 
	 * @return 0:状态为00X，返回报错;1:存在相同名称的策略，不可以新增;
	 */
	@Override
	public DmStrategyPO add(DmStrategyPO record) throws BaseAppException {
		logger.debug("添加策略record={0}", record);
		/*
		 * 替换，数据库必填，前台空值，的字段的值 所有非空字段： 不需要替换： 需要替换：
		 */
		if (Utils.isEmpty(record.getConcurrentNumber())) {
			record.setConcurrentNumber(1);
		}
		Date nowDate = new Date();
		record.setStateDate(nowDate);
		int dmStrategyId = 0;
		// 通过前台传回来的ID，从数据库里找，是否已经有这条数据了
		DmStrategyPO dsPO = dmStrategyDao.selectByPrimaryKey(record.getDmStrategyId());
		if (Utils.isEmpty(dsPO)) {// 不存在这条记录，说明是新增
			dmStrategyDao.insertSelective(record);
		} else {
			dmStrategyId = dsPO.getDmStrategyId();
			record.setDmStrategyId(dmStrategyId);
			if (dsPO.getState().equals(Status.DRAFT.toString())) {// 草稿箱，点击提交
				// 草稿箱状态为00D或者0DA，直接修改草稿箱，状态改为00A
				record.setStateDate(nowDate);
				dmStrategyDao.updateByPrimaryKeySelective(record);
			} else {// 修改，点击提交
				// 先把原来的记录状态改成00X
				dsPO.setState(Status.CANCELLED.toString());
				dsPO.setStateDate(nowDate);
				dmStrategyDao.updateByPrimaryKeySelective(dsPO);
				// 再新增一条序号为 +1 的记录
				record.setSeqNbr(dsPO.getSeqNbr() + 1);
				dmStrategyDao.insertSelective(record);
			}
		}
		return record;
	}

	/**
	 * 添加策略组，主要是为了获取策略组号、策略组名称、计划ID
	 * 
	 * @return
	 * @throws BaseAppException
	 */
	@Override
	public DmStrategyPO addStrategyGroup(DmPlanPO dpPO) throws BaseAppException {
		int dmPlanId = dpPO.getDmPlanId();
		DmStrategyPO dsPO = new DmStrategyPO();
		if (Utils.isEmpty(dmPlanDao.selectByPrimaryKey(dmPlanId))
				&& dmPlanDao.selectByPlanName(dpPO.getPlanName()) != 0) {// 不存在这个ID的计划，且存在相同名称的计划
			dsPO.setDmPlanId(-1);
			return dsPO;
		}
		int dmStrategyId = sequenceGenerator.sequenceIntValue("DM_STRATEGY", "DM_STRATEGY_ID");
		if (dmPlanId == 0) {
			dmPlanId = sequenceGenerator.sequenceIntValue("DM_PLAN", "DM_PLAN_ID");
		}
		dsPO.setDmPlanId(dmPlanId);
		dsPO.setGroupNbr(dmStrategyId);
		dsPO.setGroupName("策略组" + (dmPlanRelationDao.selectGroupByDmPlan(dmPlanId).size() + 1));
		return dsPO;
	}

	@Override
	public int update(DmStrategyPO record) throws BaseAppException {
		logger.debug("update begin...record={0}", record);
		return dmStrategyDao.updateByPrimaryKeySelective(record);
	}

	@Override
	public int drag(Integer moveId, Integer targetId, String moveType) throws BaseAppException {
		DmPlanRelationPO record = new DmPlanRelationPO();
		record.setState(Status.SUCCESS.toString());
		record.setDmStrategyId(moveId);
		DmPlanRelationPO moveDPR = dmPlanRelationDao.selectByDmStrategyId(record);
		int moveEO = moveDPR.getExecOrder();// 拖动策略的顺序
		int moveToEO = 0;// 拖动的策略，最终移动的位置(顺序)
		if ("inner".equals(moveType)) {// 拖动到策略组
			List<DmPlanRelationPO> moveDPRList = dmPlanRelationDao.selectByGroupNbr(moveDPR);
			// 逐个更新拖动策略所在组的顺序
			for (int i = moveEO; i < moveDPRList.size(); i++) {
				moveDPRList.get(i).setExecOrder(i);
				dmPlanRelationService.update(moveDPRList.get(i));
			}
			record.setGroupNbr(targetId);
			moveToEO = dmPlanRelationDao.selectByGroupNbr(record).size() + 1;
			// 更新拖动策略的关系表：顺序为moveToEO
			moveDPRList.get(moveEO - 1).setExecOrder(moveToEO);
			// 更新组号，即targetId
			moveDPRList.get(moveEO - 1).setGroupNbr(targetId);
			dmPlanRelationService.update(moveDPRList.get(moveEO - 1));
			return 1;
		} else {
			record.setDmStrategyId(targetId);
			DmPlanRelationPO targetDPR = dmPlanRelationDao.selectByDmStrategyId(record);
			int targetEO = targetDPR.getExecOrder();// 目标策略的顺序
			// 两个策略在同一组
			if (moveDPR.getGroupNbr().equals(targetDPR.getGroupNbr())) {
				List<DmPlanRelationPO> dprList = dmPlanRelationDao.selectByGroupNbr(targetDPR);
				if (moveEO < targetEO) {// 拖动策略顺序小于目标策略顺序
					if ("next".equals(moveType)) {// 拖动策略拖动到目标策略之后
						moveToEO = targetEO;
					} else {
						moveToEO = targetEO - 1;
					}
					// 更新拖动策略的关系表：顺序为moveToEO
					dprList.get(moveEO - 1).setExecOrder(moveToEO);
					dmPlanRelationService.update(dprList.get(moveEO - 1));
					for (int i = moveEO; i < moveToEO; i++) {
						// 逐个更新策略的关系表，顺序就是i
						dprList.get(i).setExecOrder(i);
						dmPlanRelationService.update(dprList.get(i));
					}
				} else {// 拖动策略顺序大于目标策略顺序
					if ("next".equals(moveType)) {// 拖动策略拖动到目标策略之后
						moveToEO = targetEO + 1;
					} else {
						moveToEO = targetEO;
					}
					// 更新拖动策略的关系表：顺序为moveToEO
					dprList.get(moveEO - 1).setExecOrder(moveToEO);
					dmPlanRelationService.update(dprList.get(moveEO - 1));
					for (int i = moveToEO - 1; i < moveEO - 1; i++) {
						// 逐个更新策略的关系表，顺序就是i+2
						dprList.get(i).setExecOrder(i + 2);
						dmPlanRelationService.update(dprList.get(i));
					}
				}
			} else {// 两个策略不在同一组
				List<DmPlanRelationPO> moveDPRList = dmPlanRelationDao.selectByGroupNbr(moveDPR);
				List<DmPlanRelationPO> targetDPRList = dmPlanRelationDao.selectByGroupNbr(targetDPR);
				// 逐个更新拖动策略所在组的顺序
				for (int i = moveEO; i < moveDPRList.size(); i++) {
					moveDPRList.get(i).setExecOrder(i);
					dmPlanRelationService.update(moveDPRList.get(i));
				}
				if ("next".equals(moveType)) {// 拖动策略拖动到目标策略之后
					moveToEO = targetEO + 1;
				} else {
					moveToEO = targetEO;
				}
				// 更新拖动策略的关系表：顺序为moveToEO
				moveDPRList.get(moveEO - 1).setExecOrder(moveToEO);
				// 更新组号
				moveDPRList.get(moveEO - 1).setGroupNbr(targetDPR.getGroupNbr());
				dmPlanRelationService.update(moveDPRList.get(moveEO - 1));
				// 逐个更新拖动到的位置之后的顺序
				for (int i = moveToEO - 1; i < targetDPRList.size(); i++) {
					targetDPRList.get(i).setExecOrder(i + 2);
					dmPlanRelationService.update(targetDPRList.get(i));
				}
			}
			return 1;
		}
	}

	@Override
	public int delete(DmStrategyPO record) throws BaseAppException {
		logger.debug("delete begin...record={0}", record);
		Date nowDate = new Date();
		// 先把原先的记录置为00X，再新增一条00X的记录：序列号+1，员工ID更新
		// 计划策略关系表，也要一起操作

		// 获取计划策略关系对象
		DmPlanRelationPO prsPO = new DmPlanRelationPO();
		prsPO.setDmStrategyId(record.getDmStrategyId());
		prsPO.setDmPlanId(record.getDmPlanId());
		prsPO = dmPlanRelationDao.selectByPrimaryKey(prsPO);
		// 作废原先的记录：计划策略关系表
		prsPO.setState(Status.CANCELLED.toString());
		prsPO.setStateDate(nowDate);
		dmPlanRelationDao.deleteByPrimaryKey(prsPO);
		// 新增记录:计划策略关系
		prsPO.setSeqNbr(prsPO.getSeqNbr() + 1);
		prsPO.setStaffId(record.getStaffId());
		dmPlanRelationDao.insertSelective(prsPO);

		// 获取策略对象
		DmStrategyPO dsPO = dmStrategyDao.selectByPrimaryKey(record.getDmStrategyId());
		// 新增记录:策略
		dsPO.setSeqNbr(dsPO.getSeqNbr() + 1);
		dsPO.setState(Status.CANCELLED.toString());
		dsPO.setStateDate(nowDate);
		dsPO.setStaffId(record.getStaffId());
		dmStrategyDao.insertSelective(dsPO);
		// 作废原先的记录：策略
		record.setState(Status.CANCELLED.toString());
		record.setStateDate(nowDate);
		return dmStrategyDao.deleteByPrimaryKey(record);
	}

	@Override
	public DmStrategyPO addSomeInfoOfOneStrategy(DmSrcTablePO record, String state) throws BaseAppException, Exception {
		logger.debug("保存一个策略下的部分信息，包括：计划策略关系、策略、策略数据关系、源数据----源数据={0}", record);
		DmStrategyPO dsPO = new DmStrategyPO();
		Date nowDate = new Date();
		Date createDate = new Date();
		// 解析数据
		TableNamePO[] tableNameArray = record.getTableNameArray();
		record.setTableName(tableNameArray[0].getValue());// 基表名

		// 主键 生成器，获取从表源数据对象ID
		int subSourceDataId = 0;
		// 主键 生成器，获取分表定义表ID
		int subTableDefineId = 0;
		// 策略ID
		if (record.getDmStrategyId() == null || record.getDmStrategyId() == 0) {
			// 主键生成器，获取策略ID
			int dmStrategyId = sequenceGenerator.sequenceIntValue("DM_STRATEGY", "DM_STRATEGY_ID");
			record.setDmStrategyId(dmStrategyId);
		}
		// 源数据对象ID
		if (record.getSourceDataId() == null || record.getSourceDataId() == 0) {
			// 主键 生成器，获取源数据对象ID
			int sourceDataId = sequenceGenerator.sequenceIntValue("SOURCE_DATA", "SOURCE_DATA_ID");
			record.setSourceDataId(sourceDataId);
		}

		// 计划、策略关系表
		DmPlanRelationPO dprPO = new DmPlanRelationPO();
		dprPO.setDmPlanId(record.getDmPlanId());
		dprPO.setSeqNbr(1);
		dprPO.setDmStrategyId(record.getDmStrategyId());
		dprPO.setGroupNbr(record.getDmStrategyGroupNum());
		dprPO.setExpDate(record.getExpDate());
		dprPO.setState(state);
		dprPO.setStateDate(nowDate);
		dprPO.setStaffId(record.getStaffId());
		dmPlanRelationService.add(dprPO);

		// 策略表
		dsPO.setDmStrategyId(record.getDmStrategyId());
		dsPO.setDmPlanId(record.getDmPlanId());
		dsPO.setSeqNbr(1);
		dsPO.setStrategyName(record.getTableName());
		dsPO.setHotDataFlag(record.getHotDataFlag());
		dsPO.setUpperCnt(record.getUpperCnt() * 10000);
		dsPO.setBatchCommitCount(record.getBatchCommitCount());
		dsPO.setConcurrentNumber(record.getConcurrentNumber());
		dsPO.setState(state);
		dsPO.setStaffId(record.getStaffId());
		add(dsPO);

		// 策略关联源数据表
		DmStrategyDataobjRelPO dsdrPO = new DmStrategyDataobjRelPO();
		dsdrPO.setDmStrategyId(record.getDmStrategyId());
		dsdrPO.setSourceDataId(record.getSourceDataId());
		dsdrPO.setObjectType(1);
		dsdrPO.setMainFlag(1);
		dsdrPO.setPriority(1);
		dsdrPO.setState(state);
		dsdrPO.setStateDate(nowDate);
		dmStrategyDataobjRelService.add(dsdrPO);

		// 源数据表
		// record.setSourceDataId(record.getSourceDataId());
		record.setSeqNbr(1);
		// 通过ID，从数据库里找，是否已经有这个表的分表定义信息
		SubTableDefineArg arg = new SubTableDefineArg();
		SubTableDefineCriteria criteria = arg.createCriteria();
		criteria.andSourceDataIdEqualTo(record.getSourceDataId());
		criteria.andStateNotEqualTo(Status.CANCELLED.toString());
		List<SubTableDefinePO> stdPOList = subTableDefineDao.selectByArg(arg);
		int seqNbr = 1;
		if (stdPOList.size() != 0) {// 已经有这个表的分表定义信息
			// 先将这些分表定义表状态改成00X
			SubTableDefinePO stdPO = new SubTableDefinePO();
			stdPO.setState(Status.CANCELLED.toString());
			stdPO.setStateDate(nowDate);
			SubTableDefineArg arg_update = new SubTableDefineArg();
			SubTableDefineCriteria criteria_update = arg_update.createCriteria();
			criteria_update.andSourceDataIdEqualTo(record.getSourceDataId());
			criteria_update.andSeqNbrEqualTo(stdPOList.get(0).getSeqNbr());
			subTableDefineDao.updateByArgSelective(stdPO, arg_update);
			seqNbr = stdPOList.get(0).getSeqNbr() + 1;
			createDate = stdPOList.get(0).getCreateDate();
		}
		if (tableNameArray.length > 1) {// 存在分表
			record.setSubFlag("1");
			for (int i = 0; i < tableNameArray.length; i++) {
				// 分表定义表
				SubTableDefinePO stdPO = new SubTableDefinePO();
				subTableDefineId = sequenceGenerator.sequenceIntValue("SUB_TABLE_DEFINE", "DATA_ID");
				stdPO.setDataId(subTableDefineId);
				stdPO.setSeqNbr(seqNbr);
				stdPO.setDataType(1);
				stdPO.setPriority(i + 1);
				if ("list".equals(tableNameArray[i].getType()) || "timer".equals(tableNameArray[i].getType())
						|| "4".equals(tableNameArray[i].getType())) {
					stdPO.setSubDefineType(1);// 可变
					stdPO.setSubDefineValue(tableNameArray[i].getValue());
					if ("timer".equals(tableNameArray[i].getType())) {
						String[] timerStrs = tableNameArray[i].getValue().split(",");
						stdPO.setSubDefineValue(timerStrs[0]);
					}
					if ("4".equals(tableNameArray[i].getType())) {// 账期
						stdPO.setSubDefineValue("4");
					}
				} else {
					stdPO.setSubDefineType(0);// 固定
					stdPO.setSubDefineValue(tableNameArray[i].getValue());
				}
				stdPO.setSourceDataId(record.getSourceDataId());
				stdPO.setStaffId(record.getStaffId());
				stdPO.setState(state);
				stdPO.setStateDate(nowDate);
				stdPO.setCreateDate(createDate);
				subTableDefineService.add(stdPO);
			}
		} else {// 不存在分表
			record.setSubFlag("0");
			// 分表定义表（只保存表名）
			SubTableDefinePO stdPO = new SubTableDefinePO();
			subTableDefineId = sequenceGenerator.sequenceIntValue("SUB_TABLE_DEFINE", "DATA_ID");
			stdPO.setDataId(subTableDefineId);
			stdPO.setSeqNbr(seqNbr);
			stdPO.setDataType(1);
			stdPO.setPriority(1);
			stdPO.setSubDefineType(0);// 固定
			stdPO.setSubDefineValue(record.getTableName());
			stdPO.setSourceDataId(record.getSourceDataId());
			stdPO.setStaffId(record.getStaffId());
			stdPO.setState(state);
			stdPO.setStateDate(nowDate);
			stdPO.setCreateDate(createDate);
			subTableDefineService.add(stdPO);
		}
		record.setArchiveMode(record.getArchiveMode());// 归档方式，现在默认为条件归档
		record.setReverseFlag("0");// 是否反向归档，默认否
		record.setOneRecordSize(dmSrcTableService.getRecordSize(record.getDbLinkId(), record.getDbUserName(),
				record.getTableName()));
		for (int i = 1; i < tableNameArray.length; i++) {
			if ("timer".equals(tableNameArray[i].getType())) {// 时间变量
				String[] timerStr = tableNameArray[i].getValue().split(",");
				if ("2".equals(timerStr[0])) {// 年月
					record.setOffsetType("1");// 偏移类型
				} else if ("3".equals(timerStr[0])) {// 年月日
					record.setOffsetType("2");
				}
				record.setUpperOffset(Integer.parseInt(timerStr[1]));// 偏移量上限，小
				record.setLowerOffset(Integer.parseInt(timerStr[2]));// 偏移量下限，大
			}
			if ("4".equals(tableNameArray[i].getType())) {// 账期
				String[] timerStr = tableNameArray[i].getValue().split(",");
				if (!"".equals(timerStr[0])) {
					record.setUpperOffset(Integer.parseInt(timerStr[0]));// 偏移量上限，小
				}
				if (timerStr.length == 2) {
					record.setLowerOffset(Integer.parseInt(timerStr[1]));// 偏移量下限，大
				}
			}
		}
		record.setState(state);
		record.setStaffId(record.getStaffId());
		dmSrcTableService.add(record);

		// 从表数据
		if (record.getArchiveType() == 1) {// 关联归档
			List<SubTablePO> subTablePOList = record.getSubTables();
			int priority = 1;
			for (SubTablePO stPO : subTablePOList) {
				// 策略关联源数据表
				DmStrategyDataobjRelPO dsdrPOSub = new DmStrategyDataobjRelPO();
				// 从表源数据表
				DmSrcTablePO dstPO = new DmSrcTablePO();
				// 关联表对象（字段对应关系）
				DmTableRelPO dtrPO = new DmTableRelPO();
				if (Utils.notEmpty(stPO.getIsDelete()) && stPO.getIsDelete() == 1) {// 删除的从表
					if (stPO.getSourceDataId() == 0) {// 新建的时候删除的从表
						continue;
					}
					// 策略关联源数据表
					dsdrPOSub.setDmStrategyId(record.getDmStrategyId());
					dsdrPOSub.setSourceDataId(stPO.getSourceDataId());
					dmStrategyDataobjRelService.delete(dsdrPOSub);

					// 从表源数据表
					dstPO.setSourceDataId(stPO.getSourceDataId());
					dstPO.setStaffId(record.getStaffId());
					dmSrcTableService.delete(dstPO);

					// 从表分表定义表
					SubTableDefinePO stdPO = new SubTableDefinePO();
					stdPO.setSourceDataId(stPO.getSourceDataId());
					stdPO.setStaffId(record.getStaffId());
					subTableDefineService.delete(stdPO);

					// 关联表对象（字段对应关系）
					dtrPO.setSubDataId(stPO.getSourceDataId());
					dtrPO.setRelDataId(record.getSourceDataId());
					dtrPO.setStaffId(record.getStaffId());
					dmTableRelService.delete(dtrPO);
					continue;
				}
				priority++;
				if (stPO.getSourceDataId() == null || stPO.getSourceDataId() == 0) {
					// 从表源数据对象ID
					subSourceDataId = sequenceGenerator.sequenceIntValue("SOURCE_DATA", "SOURCE_DATA_ID");
					stPO.setSourceDataId(subSourceDataId);
				}

				// 策略关联源数据表
				dsdrPOSub.setDmStrategyId(record.getDmStrategyId());
				dsdrPOSub.setSourceDataId(stPO.getSourceDataId());
				dsdrPOSub.setObjectType(1);
				dsdrPOSub.setMainFlag(0);
				dsdrPOSub.setPriority(priority);
				dsdrPOSub.setState(state);
				dsdrPOSub.setStateDate(nowDate);
				dmStrategyDataobjRelService.add(dsdrPOSub);

				// 从表源数据表
				TableNamePO[] subTableNames = stPO.getSubTableNames();
				dstPO.setSourceDataId(stPO.getSourceDataId());
				dstPO.setSeqNbr(1);
				dstPO.setDbLinkId(stPO.getDbLinkId());
				dstPO.setDbUserName(stPO.getSubDbUserName());// 用户名，待定
				dstPO.setTableName(subTableNames[0].getValue());
				// 通过ID，从数据库里找，是否已经有这个表的分表定义信息
				SubTableDefineArg arg_sub = new SubTableDefineArg();
				SubTableDefineCriteria criteria_sub = arg_sub.createCriteria();
				criteria_sub.andSourceDataIdEqualTo(stPO.getSourceDataId());
				criteria_sub.andStateNotEqualTo(Status.CANCELLED.toString());
				List<SubTableDefinePO> stdPOList_sub = subTableDefineDao.selectByArg(arg_sub);
				int seqNbr_sub = 1;
				if (stdPOList_sub.size() != 0) {// 已经有这个表的分表定义信息
					// 先将这些分表定义表状态改成00X
					SubTableDefinePO stdPO = new SubTableDefinePO();
					stdPO.setState(Status.CANCELLED.toString());
					stdPO.setStateDate(nowDate);
					SubTableDefineArg arg_update = new SubTableDefineArg();
					SubTableDefineCriteria criteria_update = arg_update.createCriteria();
					criteria_update.andSourceDataIdEqualTo(stPO.getSourceDataId());
					criteria_update.andSeqNbrEqualTo(stdPOList_sub.get(0).getSeqNbr());
					subTableDefineDao.updateByArgSelective(stdPO, arg_update);
					seqNbr_sub = stdPOList_sub.get(0).getSeqNbr() + 1;
					createDate = stdPOList_sub.get(0).getCreateDate();
				}
				if (subTableNames.length > 1) {// 存在分表
					dstPO.setSubFlag("1");
					for (int i = 0; i < subTableNames.length; i++) {
						SubTableDefinePO stdPO = new SubTableDefinePO();
						subTableDefineId = sequenceGenerator.sequenceIntValue("SUB_TABLE_DEFINE", "DATA_ID");
						stdPO.setDataId(subTableDefineId);
						stdPO.setSeqNbr(seqNbr_sub);
						stdPO.setDataType(1);
						stdPO.setPriority(i + 1);
						if ("variable".equals(subTableNames[i].getType())) {
							stdPO.setSubDefineType(1);// 可变
							String[] variableStrs = subTableNames[i].getValue().split(",");
							if ("0".equals(variableStrs[1])) {// 与主表字段一样
								stdPO.setSubDefineValue(variableStrs[0]);
							} else {
								stdPO.setSubDefineValue(variableStrs[1]);
							}
							stdPO.setSubRefCol(variableStrs[0]);
						} else {
							stdPO.setSubDefineType(0);// 固定
							stdPO.setSubDefineValue(subTableNames[i].getValue());
						}
						stdPO.setSourceDataId(stPO.getSourceDataId());
						stdPO.setStaffId(record.getStaffId());
						stdPO.setState(state);
						stdPO.setStateDate(nowDate);
						stdPO.setCreateDate(createDate);
						subTableDefineService.add(stdPO);
					}
				} else {
					SubTableDefinePO stdPO = new SubTableDefinePO();
					subTableDefineId = sequenceGenerator.sequenceIntValue("SUB_TABLE_DEFINE", "DATA_ID");
					stdPO.setDataId(subTableDefineId);
					stdPO.setSeqNbr(seqNbr_sub);
					stdPO.setDataType(1);
					stdPO.setPriority(1);
					stdPO.setSubDefineType(0);// 固定
					stdPO.setSubDefineValue(dstPO.getTableName());
					stdPO.setSourceDataId(stPO.getSourceDataId());
					stdPO.setStaffId(record.getStaffId());
					stdPO.setState(state);
					stdPO.setStateDate(nowDate);
					stdPO.setCreateDate(createDate);
					subTableDefineService.add(stdPO);
				}
				dstPO.setDiiPOList(stPO.getDiiPOList());
				dstPO.setMainDataId(record.getSourceDataId());
				dstPO.setOneRecordSize(dmSrcTableService.getRecordSize(record.getDbLinkId(), record.getDbUserName(),
						record.getTableName()));
				dstPO.setState(state);
				dstPO.setStaffId(record.getStaffId());
				dmSrcTableService.add(dstPO);

				// 关联表对象（字段对应关系）
				dtrPO.setSubDataId(stPO.getSourceDataId());
				dtrPO.setSeqNbr(1);
				dtrPO.setRelDataId(record.getSourceDataId());
				String relMapCols = stPO.getRelMapCols();
				String subMapCols = stPO.getSubMapCols();
				dtrPO.setRelMapCols(relMapCols.substring(10, relMapCols.length()));
				dtrPO.setSubMapCols(subMapCols.substring(10, subMapCols.length()));
				dtrPO.setState(state);
				dtrPO.setStaffId(record.getStaffId());
				dmTableRelService.add(dtrPO);
			}
		}
		dsPO.setDmSrcTablePO(record);
		return dsPO;
	}
}
